# coding=utf-8
from django.template import Context, loader
from django.http import HttpResponse
from ltyxapp.models import *
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.shortcuts import RequestContext
from django.core.paginator import PageNotAnInteger, Paginator, InvalidPage, EmptyPage
def blog_index(request,blogtype):   
    t = loader.get_template('blog/blog_list.html')
    if  blogtype=='':
        blog=Blog.objects.all()
        blogtype='all'
    else:
        blog=Blog.objects.filter(types=blogtype)[:6]
    blog_original=Blog.objects.filter(types='Y')
    blog_reproduced=Blog.objects.filter(types='Z')



    after_range_num = 3        
    befor_range_num = 3     
    try:                    
        page = int(request.GET.get("page",1))
        if page < 1:
            page = 1
    except ValueError:
        page = 1
    paginator = Paginator(blog,8)   
    try:                     
        blog = paginator.page(page)
    except(Empte,InvalidPage,PageNotAnInteger):
        blog = paginator.page(paginator.num_pages)
    if page >= after_range_num:
        page_range = paginator.page_range[page-after_range_num:page+befor_range_num]
    else:
        page_range = paginator.page_range[0:int(page)+befor_range_num]   
                
    # return render_to_response('user/mysitelist.html',{'novist':novist,'sorts':sorts,'sites':sites,'page_range':page_range,})












    c = Context({
                 'blog':blog,
                 'blog_original':len(blog_original),
                 'blog_reproduced':len(blog_reproduced),
                 'blogtype':blogtype,
                 'page_range':page_range,
    })
    return HttpResponse(t.render(c))

def blog_detail(request,blogtype,blogid):   
    t = loader.get_template('blog/detail.html')
    detailblog=Blog.objects.get(id=int(blogid))
    blog_original=Blog.objects.filter(types='Y')
    blog_reproduced=Blog.objects.filter(types='Z')
    c = Context({
                 'blog':detailblog,
                 'blog_original':len(blog_original),
                 'blog_reproduced':len(blog_reproduced),
                 'blogtype':blogtype,
    })
    return HttpResponse(t.render(c))

